from com.mysqlconnection import mysql_connect
from  init_cs import dictfetchall
from cs.configfile_read import *
import CloudStack
import base64
import hmac
import hashlib
import json
import urllib
import sys

listinstance_sql='SELECT id,NAME,instance_name,(SELECT account_name FROM account WHERE id=account_id) AS "account",private_ip_address,state,(SELECT NAME FROM vm_template WHERE id=vm_template_id) AS template_name, (SELECT NAME FROM host WHERE id = host_id) AS "name",created FROM vm_instance WHERE removed IS NULL ORDER BY account DESC'
user_ips_sql='SELECT u.source_network_id,u.public_ip_address,n.`name` FROM user_ip_address AS u,networks AS n WHERE u.source_network_id=n.id  AND u.`state` ="Free" AND n.name IS NOT NULL;'
ip_and_instancename='SELECT instance_name,private_ip_address FROM vm_instance WHERE removed IS NULL'
list_runing_instance='SELECT id,NAME,instance_name,(SELECT account_name FROM account WHERE id=account_id) AS "account",private_ip_address,state,(SELECT NAME FROM vm_template WHERE id=vm_template_id) AS template_name, (SELECT NAME FROM host WHERE id = host_id) AS "name",created FROM vm_instance WHERE removed IS NULL AND state = "Running" ORDER BY account DESC'

def get_all_instances_list():
    cnn=mysql_connect()
    cnn.execute(listinstance_sql)
    return dictfetchall(cnn)

def get_all_runing_instances_list():
    cnn=mysql_connect()
    cnn.execute(list_runing_instance)
    return dictfetchall(cnn)


def get_free_IP_Parameter():
    cnn=mysql_connect()
    cnn.execute(user_ips_sql)
    return dictfetchall(cnn)

def get_instance_ip_info():
    cnn=mysql_connect()
    cnn.execute(ip_and_instancename)
    return dictfetchall(cnn)

def deploy_instance(cmdargs): 
    global file
    file=''
    pacth=os.path.abspath('.')
    f2='F:\code\cs-bs\cs\db.ini'
    f1='/home/cs-bs/cs/db.ini'
    for i in (f1,f2):
        if os.path.exists(i):
            file=i
    if file == '':
        print 'not find the file'
        sys.exit()
    db=Api_connect(file)
    apikey=str(db.get_api_key())
    seckey=str(db.get_sec_Key())
    api_url=str(db.get_url_path())
    
    api = api_url
    apikey = apikey
    secret = seckey
    cloudstack = CloudStack.Client(api, apikey, secret)
    print cmdargs
    job = cloudstack.deployVirtualMachine(cmdargs)
    print job['id']
    vm={'id':job['id']}
    instance = cloudstack.listVirtualMachines(vm)
    return instance
    

    